<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\components;

use Yii;
use app\models\Upfile;
use \app\components\Imgcompress;
/**
 * Description of UploadFile
 *
 * @author song
 */
class UploadFile {

    const D_ok = 'ok';
    const D_error = 'error';

    const TypeBig='big';
    const TypeSmall='small';
    /**
     * 上传文件
     */
    public static function start($file='file',$isyuantu=false) {
        $save_path = Yii::getAlias('@webroot') . '/public/Uploads/';

        $save_url = Lcms::getWeb(). 'public/Uploads/';
        //定义允许上传的文件扩展名
        $ext_arr = array(
            'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
            'media' => array('mp3','mp4','mov','jpg', 'jpeg'),
            'mp3' => array('mp3'),
                //	'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
                //'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
        );
        //最大文件大小 
        $max_size = 1024 * 1024 * 80;
                
        //PHP上传失败
        if (!empty($_FILES[$file]['error'])) {
            switch ($_FILES[$file]['error']) {
                case '1':
                    $error = '超过php.ini允许的大小。';
                    break;
                case '2':
                    $error = '超过表单允许的大小。';
                    break;
                case '3':
                    $error = '图片只有部分被上传。';
                    break;
                case '4':
                    $error = '请选择图片。';
                    break;
                case '6':
                    $error = '找不到临时目录。';
                    break;
                case '7':
                    $error = '写文件到硬盘出错。';
                    break;
                case '8':
                    $error = 'File upload stopped by extension。';
                    break;
                case '999':
                default:
                    $error = '未知错误。';
            }
            API::$errormsg=$error;
            return false;
            //self::alert($error, self::D_error);
        }

        if (empty($_FILES)) {
            ///self::alert('文件上传错误，没有上传内容', self::D_error);
            API::$errormsg='文件上传错误，没有上传内容';
            return false;
        }

        //原文件名
        $file_name = $_FILES[$file]['name'];
        //服务器上临时文件名
        $tmp_name = $_FILES[$file]['tmp_name'];
        $md5=md5_file($tmp_name);////原图的
        ///
       $url=Upfile::getUrl($md5);
       if($url){
            return [ 'img'=>$url];
       }
        ///
        ///
        ///
        //文件大小
        $file_size = $_FILES[$file]['size'];
        //检查文件名
        if (!$file_name) {
            ///self::alert("请选择文件。", self::D_error);
            API::$errormsg="请选择文件。";
             return false;
        }
        /// var_dump($file_name,$file_size);exit; 
        //检查是否已上传
        if (@is_uploaded_file($tmp_name) === false) {
         ///   self::alert("上传失败。", self::D_error);
            API::$errormsg="上传失败。";
             return false;
        }

        //检查文件大小
        if ($file_size > $max_size) {
          ///  self::alert("上传文件大小超过限制。", self::D_error);
             API::$errormsg="上传文件大小超过限制。";
             return false;
        }
        //检查目录名
        $dir_name = empty($_GET['dir']) ? 'image' : trim($_GET['dir']);


        if (empty($ext_arr[$dir_name])) {
          ///  self::alert("目录名不正确。", self::D_error);
            API::$errormsg="目录名不正确。";
             return false;
        }
        //获得文件扩展名
        $temp_arr = explode(".", $file_name);
        $file_ext = array_pop($temp_arr);
        $file_ext = trim($file_ext);
        $file_ext = strtolower($file_ext);


        //检查扩展名
        if (in_array($file_ext, $ext_arr[$dir_name]) === false) {
          ///  self::alert("上传文件扩展名是不允许的扩展名。\n只允许" . implode(",", $ext_arr[$dir_name]) . "格式。", self::D_error);
            API::$errormsg="上传文件扩展名是不允许的扩展名".$file_ext."。\n只允许" . implode(",", $ext_arr[$dir_name]) . "格式。";
             return false;
        }


        //创建文件夹
        if ($dir_name !== '') {
            $save_path .= $dir_name . "/";
            $save_url .= $dir_name . "/";
            if (!file_exists($save_path)) {
                //   echo $save_path;  exit;
                mkdir($save_path);
            }
        }
        $ymd = date("Ymd");
        $save_path .= $ymd . "/";
        $save_url .= $ymd . "/";
        if (!file_exists($save_path)) {
            mkdir($save_path);
        }
        //新文件名
        $new_file_name = date("YmdHis") . '_' . rand(10000, 99999);// . '.' . $file_ext;


        $big=$new_file_name.self::TypeBig.'.'.$file_ext;///大图的文件名
        $sm=$new_file_name.self::TypeSmall.'.'.$file_ext;///小图的文件名


        if($isyuantu) {

            copy($tmp_name,$save_path . $big);
        }else{
            (new \app\components\Imgcompress($tmp_name, 0.8))->compressImg(
                $save_path . $big);
        }

        (new \app\components\Imgcompress($tmp_name,0.3))->compressImg(
            $save_path.$sm);
        $imgUrl=Fun::pImg($save_url.$sm);
        $bigUrl=Fun::pImg($save_url.$big);
        Upfile::addjilu($save_path.$sm, $imgUrl,$md5);
        unlink($tmp_name);//删除原图
        return [
            'img'=>$imgUrl//,
           // 'big'=>$bigUrl
        ];
    }




    /**
     * 根据编码上传
    */
    public static function forBaseCodeUpfile($base64)
    {
        $md5 = md5_file($base64);////原图的
        $url=Upfile::getUrl($md5);
        if($url){
            return $url;
        }

        $imgData =self::getImgData($base64);


        $save_path = Yii::getAlias('@webroot') . '/public/Uploads/';

        $save_url = Lcms::getWeb(). 'public/Uploads/';
        $file_ext='jpg';
        $dir_name="image";
        //创建文件夹
        if ($dir_name !== '') {
            $save_path .= $dir_name . "/";
            $save_url .= $dir_name . "/";
            if (!file_exists($save_path)) {
                mkdir($save_path);
            }
        }
        $ymd = date("Ymd");
        $save_path .= $ymd . "/";
        $save_url .= $ymd . "/";
        if (!file_exists($save_path)) {
            mkdir($save_path);
        }
        //新文件名
        $new_file_name = date("YmdHis") . '_' . rand(10000, 99999);// . '.' . $file_ext;
        $big=$new_file_name.self::TypeBig.'.'.$file_ext;///大图的文件名
        $sm=$new_file_name.self::TypeSmall.'.'.$file_ext;///小图的文件名
        if (!file_put_contents($save_path . $big, $imgData)) {
            OA::Json(1, '错误');
        }

        (new Imgcompress($save_path . $big, 0.3))->compressImg(
            $save_path . $sm);
        (new Imgcompress($save_path . $big, 0.8))->compressImg(
            $save_path . $big);

    //    $save_url=Fun::pImg($save_url.$sm);
        $save_url=$save_url.$sm;
       // var_dump($save_url, $save_path . $big);exit;

        Upfile::addjilu($save_path . $sm, $save_url,$md5);
        return [ 'img'=>$save_url,'file'=>$save_path . $sm];
    }


    /**
     * 获取图片数据
     */
    public static function getImgData($base64)
    {
        $string = 'base64,';
        $weizhi = strpos($base64, $string) + strlen($string);
        $data = substr($base64, $weizhi);
        return base64_decode($data);
    }




    /**
     * 本地地址
    */
    static $file_path;

    static public function alert($text, $type) {
                
        $al = [
            'msg' => $text,
            'code' => $type
        ];
        echo json_encode($al);
         exit;       
    }

    /**
     * 生成一个唯一的文件路径
     */
    private function getSavePath() {
        $publicUploads = 'public/Uploads/';
        $save_path = Yii::getAlias('@webroot') . '/' . $publicUploads;
        $ymd = date("ymdH") . "/";
        $newPath = $save_path . $ymd;
        if (!file_exists($newPath)) {
            mkdir($newPath);
        }
        return [
            'save' => $newPath,
            'url' => Lcms::getWeb() . $publicUploads . $ymd
        ];
    }

    /**
     * 获取一个存储用的地址和浏览的地址
     */
    public function getSaveFilePath() {
        $ex = $this->getSavePath();
        for ($i = 0; $i < 5; $i++) {
            $new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.png';
            if (!file_exists($ex['save'] . $new_file_name)) {
                return [
                    'save' => $ex['save'] . $new_file_name,
                    'url' => $ex['url'] . $new_file_name
                ];
            }
        }
        Fun::showmsg("系统错误");
        return false;
    }



    /**
     * 保存图片数据
     */
    public function saveBase64_2($base64) {
        $pa = $this->getSaveFilePath();
        $imgData = $this->getImgData($base64);
        
        $imgObj=$this->openStrBase64Pinjie($imgData);
        ///  header('Content-Type:image/png'); imagepng($imgObj ); exit;
         imagepng($imgObj,$pa['save']); 
         return $pa;
        /*
        if (file_put_contents($pa['save'], $imgData)) {
            return $pa;
        } else {
            API::$errormsg = '上传图片错误';
            return false;
        }
        */
    }
     /**
     * 保存图片数据
     */
    public function saveBase64($base64) {
        $pa = $this->getSaveFilePath();
        $imgData = $this->getImgData($base64);
        /*
        $imgObj=$this->openStrBase64Pinjie($imgData);
        ///  header('Content-Type:image/png'); imagepng($imgObj ); exit;
         imagepng($imgObj,$pa['save']); 
         return $pa*/
       
        if (file_put_contents($pa['save'], $imgData)) {
            return $pa;
        } else {
            API::$errormsg = '上传图片错误';
            return false;
        }
       
    }
                
}
